package com.aabte.weather.city;

import com.aabte.weather.city.api.City;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Slf4j
@Service
public class CityDataServiceImpl implements CityDataService {


    @Override
    public List<City> listCity() {
        log.info("Start listCity.");
        Resource resource = new ClassPathResource("citylist.xml");
        StringBuilder buffer = new StringBuilder();
        try (BufferedReader br = new BufferedReader(
                new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8))) {
            String line;

            while ((line = br.readLine()) != null) {
                buffer.append(line);
            }
            CityList cityList = XmlBuilder.xmlStrToObject(CityList.class, buffer.toString());
            log.info("End listCity.");
            return cityList.getCityList();
        } catch (IOException e) {
            throw new CityListQueryException("get city list fail.", e);
        } catch (Exception e) {
            throw new CityListQueryException("xml convert to object fail.", e);
        }
    }
}
